package com.example.demo.command;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ch.selise.exercise.pattern.notepad.command.CommandExecutor;
import ch.selise.exercise.pattern.notepad.command.GetCommandParameter;
import ch.selise.exercise.pattern.notepad.exception.EmptyStackException;
import ch.selise.exercise.pattern.notepad.exception.ExecuteException;
import ch.selise.exercise.pattern.notepad.exception.UnsupportedCommandException;
import ch.selise.exercise.pattern.notepad.storage.AppStorageSingleton;

import com.example.demo.views.DataEntryTable;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Table;

public class MenuCommand implements MenuBar.Command{

	private static final long serialVersionUID = 1L;
	private String command = null;
	private Table tableX = null;
	
	public MenuCommand(String command) {
		super();
		this.command = command;
	}
	
	public MenuCommand(String command, Table table) {
		this(command);
		this.tableX = table;
	}

	@Override
	public void menuSelected(MenuItem selectedItem) {
		
		System.out.println(command);
		CommandExecutor commandExecutor = CommandExecutor.getInstance();
		try {
			commandExecutor.executeCommand(new GetCommandParameter(getCommand(), null, 0));
		}  catch (ExecuteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EmptyStackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (UnsupportedCommandException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally{
			reloadTable();
		}
	}
	
	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public Table getTableX() {
		return tableX;
	}

	public void setTableX(Table tableX) {
		this.tableX = tableX;
	}
	
	protected void reloadTable() {
		
		//Loading data if refresh.
		((DataEntryTable) getTableX()).deleteAllItems(false);
		List<Map<String, Object>> dataSet = new ArrayList<Map<String,Object>>();		
		for (String entry : AppStorageSingleton.getInstance().getText()) {
			Map<String, Object> x = new HashMap<String, Object>();
			x.put("Text", entry);
			x.put("Edit", "Edit");
			x.put("Delete", "Del");
			dataSet.add(x);
		}
		((DataEntryTable) getTableX()).loadOrderdData(dataSet, false);
		//
	}
}
